﻿using eslib.tools.config;
using Newtonsoft.Json;
using RestSharp;

namespace SpeechLib
{
    public static class SpeechApi
    {
        public static string GetAccessToken()
        {
            var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token");

            var request = new RestRequest("", Method.Post);
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", BaiduApiSetting.Instance.API_Key);
            request.AddParameter("client_secret", BaiduApiSetting.Instance.Secret_Key);

            RestResponse response = client.Execute(request);
            return GetResult<AccessTokenResult>(response.Content).access_token;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="text">转语音的文字</param>
        /// <param name="per">播音员</param>
        /// <param name="语速">0-15，默认5，数字越大速度越快</param>
        /// <param name="音量">0-15</param>
        /// <param name="音调">0-15</param>
        /// <returns></returns>
        public static (bool success, byte[] mp3) Speech(string text, 播音员 per, int 语速 = 5, int 音量 = 5, int 音调 = 5)
        {
            var client = new RestClient($"https://tsn.baidu.com/text2audio");
            var request = new RestRequest("", Method.Post);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Accept", "*/*");

            request.AddParameter("tex", text);
            // tok 可以通过 GetFileBase64Content('access_token') 方法获取
            request.AddParameter("tok", GetAccessToken());

            request.AddParameter("cuid", BaiduApiSetting.Instance.User_Sig);   //用户唯一标识
            request.AddParameter("ctp", "1");       //客户端类型选择，web端填写固定值1        
            request.AddParameter("lan", "zh");      //固定值zh
            request.AddParameter("spd", $"{语速}");       //语速，取值0-15，默认为5中语速。数字越大速度越快
            request.AddParameter("pit", $"{音调}");       //音调
            request.AddParameter("vol", $"{音量}");       //音量
            request.AddParameter("per", $"{(int)per}");       //度小宇=1，度小美=0，度逍遥（基础）=3，度丫丫=4
            request.AddParameter("aue", "3");       //为mp3格式(默认)
            RestResponse response = client.Execute(request);

            bool success = response.ContentType == "audio/mp3";
            return (success, response.RawBytes);
        }



        /// <summary>
        /// 长语音合成
        /// </summary>
        /// <param name="text"></param>
        /// <param name="per"></param>
        /// <param name="音频格式">"mp3-16k"，"mp3-48k"，"wav"，"pcm-8k"，"pcm-16k"</param>
        /// <param name="语速">0-15，默认5，数字越大速度越快</param>
        /// <param name="音量">0-15</param>
        /// <param name="音调">0-15</param>
        public static (bool success, 长语音调用结果 res) LongSpeech(string[] text, 播音员 per, int 语速 = 5, string 音频格式 = "mp3-16k", int 音量 = 5, int 音调 = 5)
        {
            var client = new RestClient($"https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token={GetAccessToken()}");
            var request = new RestRequest("", Method.Post);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");

            var json = new
            {
                text = text,
                format = 音频格式,
                voice = (int)per,
                lang = "zh",
                speed = 音量,
                pitch = 音调,
                volume = 音量,
                enable_subtitle = 0
            };
            string body = GenericJsonConfig.Save(json);
            request.AddParameter("application/json", body, ParameterType.RequestBody);

            RestResponse response = client.Execute(request);
            var res = GenericJsonConfig.LoadFromString<长语音调用结果>(response.Content);
            bool success = !string.IsNullOrEmpty(res.task_id);
            return (success, res);
        }



        /// <summary>
        /// 长语音任务查询
        /// </summary>
        /// <param name="task_id"></param>
        public static (任务状态 status, 长语音合成任务查询结果 res) LongSpeechTaskCheck(string task_id)
        {
            var client = new RestClient($"https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token={GetAccessToken()}");

            var request = new RestRequest("", Method.Post);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            var body = $@"{{""task_ids"":[""{task_id}""]}}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            RestResponse response = client.Execute(request);
            var res = GenericJsonConfig.LoadFromString<长语音合成任务查询结果>(response.Content);
            return (res.tasks_info[0].Status(), res);
        }





        static T GetResult<T>(string data) where T : new()
        {
            return GenericJsonConfig.LoadFromString<T>(data);
        }

        static string BaseUrl => "https://aip.baidubce.com";

        static string GetUrl(string apiUrl)
        {
            return BaseUrl + apiUrl;
        }
    }
}